<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="岗位编码" prop="postCode">
        <el-input
          v-model="queryParams.postCode"
          placeholder="请输入岗位编码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="岗位名称" prop="postName">
        <el-input
          v-model="queryParams.postName"
          placeholder="请输入岗位名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="岗位类型" prop="postCategory">
        <el-select v-model="queryParams.postCategory" placeholder="岗位类型" clearable size="small" style="width: 180px">
          <el-option
            v-for="dict in postCategoryOptions"
            :key="dict.dictCode"
            :label="dict.dictLabel"
            :value="dict.dictCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="岗位状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="岗位状态" clearable size="small" style="width: 180px">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictCode"
            :label="dict.dictLabel"
            :value="dict.dictCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['post:sys:post']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['put:sys:post']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['delete:sys:post']"
        >删除</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['post:sys:post:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['post:sys:post:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5" style="float: right" v-if="dynamicColumnSetting">
        <el-popover
          placement="bottom"
          min-width="80"
          trigger="click"
          popper-class="col-setting-popover"
        >
          <el-button
            slot="reference"
            type="primary"
            icon="el-icon-setting"
            size="mini"
          >筛选</el-button>
          <div class="col-setting-title">显示设置</div>
          <el-checkbox-group v-model="visibleIndexs" :min="0" class="col-setting-group">
            <el-checkbox
              v-for="colInfo in columnInfos"
              :label="colInfo.index"
              :key="colInfo.index"
              :disabled="colInfo.disabled"
              v-show="!colInfo.disabled || showAlwaysShowColumnInCheckbox"
            >{{ colInfo.label }}</el-checkbox>
          </el-checkbox-group>
        </el-popover>
      </el-col>
    </el-row>

    <el-table ref="pageTable" class="loading-area" :data="postList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" v-if="columnVisibles[0]"/>
      <el-table-column label="岗位编码" align="center" prop="postCode" v-if="columnVisibles[1]"/>
      <el-table-column label="岗位名称" align="center" prop="postName" v-if="columnVisibles[2]"/>
      <el-table-column label="岗位排序" align="center" prop="orderNum" v-if="columnVisibles[3]"/>
      <el-table-column label="岗位类型" align="center" prop="postCategory" :formatter="postCategoryFormat" v-if="columnVisibles[4]"/>
      <el-table-column label="岗位状态" align="center" prop="status" :formatter="statusFormat" v-if="columnVisibles[5]"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180" v-if="columnVisibles[6]">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['put:sys:post']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['delete:sys:post']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改岗位对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="岗位名称" prop="postName">
          <el-input v-model="form.postName" placeholder="请输入岗位名称" />
        </el-form-item>
        <el-form-item label="岗位编码" prop="postCode">
          <el-input v-model="form.postCode" placeholder="请输入编码名称" />
        </el-form-item>
        <el-form-item label="岗位顺序" prop="postSort">
          <el-input-number v-model="form.orderNum" controls-position="right" :min="1" />
        </el-form-item>
        <el-form-item label="岗位状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictCode"
              :label="dict.dictCode"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="岗位类型" prop="postCategory">
          <el-radio-group v-model="form.postCategory">
            <el-radio
              v-for="dict in postCategoryOptions"
              :key="dict.dictCode"
              :label="dict.dictCode"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 岗位导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px">
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?isCovered=' + upload.isCovered"
        :disabled="upload.isUploading"
        :on-change="handleFileChange"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :on-exceed="handleExceed"
        :before-remove="beforeRemove"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.isCovered" label="覆盖已经存在的数据" />
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件，请先<el-link type="info" style="font-size:12px" @click="downloadImportTemplate">【下载Excel模板】</el-link></div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="upload.isUploading" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 岗位导出列设置对话框 -->
    <el-dialog
      title="请选择需要导出的列"
      class="dyn-col-ctn"
      :visible.sync="dynColSettingDialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <el-checkbox-group v-model="exportColumnNames">
        <el-checkbox
          v-for="colInfo in columnInfos"
          :label="colInfo.colName"
          :key="colInfo.index"
        >{{ colInfo.label }}</el-checkbox>
      </el-checkbox-group>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dynColSettingCancel">取消</el-button>
        <el-button type="primary" @click="dynColSettingConfirm">导出</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listPost, getPost, deletePost, addPost, updatePost,exportPost } from "@/api/sys/post";
import store from "@/store";
import qs from 'qs'
import {getToken,isTokenValid} from '@/utils/auth'
import { beforeUpload } from "@/utils/commonUtil";
import {MessageBox} from "element-ui";
export default {
  name: "Post",
  data() {
    return {
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 岗位类型字典
      postCategoryOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        postCode: undefined,
        postName: undefined,
        status: undefined,
        postCategory: undefined
      },
      // 导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否覆盖已经存在的用户数据
        isCovered: false,
        // 设置上传的请求头部
        headers: { Authorization: getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/api/sys/post/import"
      },
      dynColSettingDialogVisible: false, // '导出列设置'弹窗开关
      columnInfos: [], // 所有列信息
      exportColumnNames: [], // 导出列集合
      showAlwaysShowColumnInCheckbox:true,
      dynamicColumnSetting:true,
      columnVisibles: new Array(7).fill(true),//设置列可见性
      visibleIndexs: [], // 可见列的下标集合
      alwaysShowColumnIndexs:[1,2],//总是显示的列的下标（不可隐藏的列）,列下标从 0 开始
      hidenColumnIndexs:[],//隐藏列的下标集合
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        postName: [
          { required: true, message: "岗位名称不能为空", trigger: "blur" }
        ],
        postCode: [
          { required: true, message: "岗位编码不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "岗位状态不能为空", trigger: "blur" }
        ],
        postCategory: [
          { required: true, message: "岗位类型不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("post_status").then(res => {
      this.statusOptions = [];
      res.data.forEach((dict)=>{
        let tmpDict = {};
        tmpDict.dictCode = Number(dict.dictCode);//数据类型转换，el-select数据回显数据类型必须要一致
        tmpDict.dictLabel = dict.dictLabel;
        this.statusOptions.push(tmpDict);
      });
    });
    this.getDicts("post_category").then(res => {
      this.postCategoryOptions = [];
      res.data.forEach((dict)=>{
        let tmpDict = {};
        tmpDict.dictCode = Number(dict.dictCode);//数据类型转换，el-select数据回显数据类型必须要一致
        tmpDict.dictLabel = dict.dictLabel;
        this.postCategoryOptions.push(tmpDict);
      });
    });
  },
  methods: {
    /** 查询岗位列表 */
    getList() {
      listPost(this.queryParams).then(response => {
        this.postList = response.data.rows;
        this.total = response.data.total;
      });
    },
    // 岗位状态字典翻译
    statusFormat(row) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    //岗位类型字典翻译
    postCategoryFormat(row) {
      return this.selectDictLabel(this.postCategoryOptions, row.postCategory);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        postCode: undefined,
        postName: undefined,
        orderNum: 1,
        status: 0,
        postCategory:1,
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加岗位";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const postId = row.id || this.ids
      getPost(postId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改岗位";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            updatePost(this.form).then(response => {
              if (response.code === 0) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addPost(this.form).then(response => {
              if (response.code === 0) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const postIds = row.id || this.ids;
      this.$confirm('是否确认删除岗位ID为"' + postIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return deletePost(postIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport(row) {
      let that = this
      // 重置导出列集合
      this.exportColumnNames = [];
      //导出列设置中默认选中所有的列
      this.columnInfos.forEach(
        columnInfo => (that.exportColumnNames.push(columnInfo.colName))
      );
      this.dynColSettingDialogVisible = true
    },
    dynColSettingCancel() {
      this.dynColSettingDialogVisible = false;
      // 重置导出列集合
      this.exportColumnNames = [];
    },
    dynColSettingConfirm(row) {
      const postIds = row.id || this.ids;
      const queryParams = this.queryParams;
      queryParams.postIds = postIds
      queryParams.exportColumnNames = this.exportColumnNames
      //导出数据
      exportPost(queryParams).then(res => {
        if(res.code===0){
          //导出成功后，服务端返回生成的Excel的下载地址和文件名
          let fileUrl = res.data.fileUrl;
          let fileName = res.data.originalFileName;
          this.download(fileUrl,fileName);//调用服务端接口下载文件
        }else {
          this.msgError(res.msg);
        }
      }).catch(function() {});
      this.dynColSettingDialogVisible = false;
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "导入岗位";
      this.upload.open = true;
      this.upload.isCovered = false
      if(this.$refs.upload){
        this.$refs.upload.clearFiles();
      }
    },
    /** 下载模板操作 */
    downloadImportTemplate() {
      if(!isTokenValid()){//Token已经失效
        MessageBox.confirm(
          '登录状态已过期，请重新登录',
          '系统提示',
          {
            showCancelButton:false,
            confirmButtonText: '重新登录',
            type: 'warning'
          }
        ).then(() => {
          store.dispatch('LogOut').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        })
        return
      }
      window.open(process.env.VUE_APP_BASE_API+'/api/sys/post/import/template?Authorization='+getToken());
    },
    //选择上传文件后
    handleFileChange(file){
      const typeList = ["xls", "xlsx"];//允许上传的文件类型
      if(!beforeUpload(file,typeList)){
        this.$message.error('选择的文件不正确，请上传正确的Excel文件')
        this.$refs.upload.clearFiles();
      }
    },
    // 文件超出个数限制时的钩子
    handleExceed(file, fileList) {
      this.$message.error('只能上传一个文件')
    },
    // 删除文件之前的钩子，参数为上传的文件和文件列表，若返回 false 或者返回 Promise 且被 reject，则停止上传。
    beforeRemove(file, fileList) {
      // 增加一个询问框
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    oprColumns(indexs, isShow) {
      let self = this;
      indexs.forEach(index => {
        self.$set(self.columnVisibles, index, isShow);
      });
    }
  },
  mounted() {
    let self = this;
    if (self.$refs.pageTable.$slots.default) {
      let columnIndex = 0;
      self.$refs.pageTable.$slots.default.forEach((columnIns, index) => {
        if (columnIns.componentOptions === undefined) {
          return;
        }
        let props = columnIns.componentOptions.propsData;
        if (
          props.prop === undefined ||
          props.type === "selection" ||
          props.type === "index"
        ) {
          return;
        }
        // 保存所有列的信息
        let label = props.label
        let colName = props.prop
        self.columnInfos.push({
          label: label,
          colName: colName,
          index: columnIndex,
          disabled: false
        })
        // 记录初始展示的列的下标
        if (self.hidenColumnIndexs.indexOf(columnIndex) === -1) {
          self.visibleIndexs.push(columnIndex);
        }
        columnIndex++
      })
      // 处理总是显示的列（不可隐藏的列）
      self.alwaysShowColumnIndexs.forEach(
        index => (self.columnInfos[index].disabled = true)
      );
      // 处理初始隐藏的列
      self.oprColumns(self.hidenColumnIndexs, false);
    }
  },
  beforeUpdate() {
    let self = this;
    self.$nextTick(_ => {
      self.$refs.pageTable.doLayout();
    });
  },
  watch: {
    visibleIndexs(newValue, oldValue) {
      let self = this;
      let willHideIndexs = [], willShowIndexs = [];
      willShowIndexs = newValue.filter(index => {
        return oldValue.indexOf(index) === -1;
      });
      willHideIndexs = oldValue.filter(index => {
        return newValue.indexOf(index) === -1;
      });
      self.oprColumns(willShowIndexs, true);
      self.oprColumns(willHideIndexs, false);
    }
  }
}
</script>
